package com.androidlab.task1;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;

public class PositionLoggerService extends Service implements LocationListener {
	LocationManager locationmanager;
	double longitude;
	double latitude;
	Location lastLocation;
	double distanceTravelled = 0;
	double avgSpeed = 0;
	
	public IBinder onBind(Intent arg0) {
		return iBinder;
	}
	
	public void onCreate(){
		super.onCreate();
		locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//		Location location = locationmanager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//		longitude = location.getLongitude();
//		latitude = location.getLatitude();
		locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		
	}
	
	public void onDestroy(){
		super.onDestroy();
	}
	
	public void updateGpxFile(){
		File sdCard = Environment.getExternalStorageDirectory(); 
		if(sdCard.canWrite()){
			try {
				File gpxFile = new File(sdCard,"gpxfile.txt");
				gpxFile.createNewFile();
				FileWriter gpxWriter = new FileWriter(gpxFile);
				BufferedWriter out = new BufferedWriter(gpxWriter);
				out.write( (int) longitude);
				out.write((int) latitude);
				out.close();
				latitude = -100;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public final service.Stub iBinder = new service.Stub() {
		
		public double getLat() throws RemoteException {
			
			return latitude;
		}

		public double getAvgSpeed() throws RemoteException {
			return avgSpeed;
		}

		public double getDistance() throws RemoteException {
//			return distanceTravelled;
			return new Random().nextInt();
		}

		public double getLong() throws RemoteException {
			return longitude;
		}
	};

	public void onLocationChanged(Location loc) {
	
		longitude = loc.getLongitude();
//		latitude = loc.getLatitude();
		
		if(lastLocation != null){
//			latitude = -100;
			distanceTravelled += loc.distanceTo(lastLocation);
			double lastTime = lastLocation.getTime();
			double currentTime = loc.getTime();
			avgSpeed = distanceTravelled / (currentTime - lastTime);
		}

		lastLocation = loc;
		
		updateGpxFile();
	}

	public void onProviderDisabled(String arg0) {
		
	}

	public void onProviderEnabled(String arg0) {
		
	}

	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		
	}
}
